import { ACCESSTOKEN } from '@/store/state-types'
import { getToken } from '@/utils/stroage/token'
import router from '@/router'
const requiredTokenURL = [
  '/user/getUserInfo',
  '/user/myArticle',
  '/user/userDataList',
  '/user/update',
  '/common/upload?type=images',
  '/user/addArticle',
  '/index/show'
]
const queryURL = '/user/userDataHandle'

const passStatus = [200]
const statusIsPass = function (status) {
  return passStatus.includes(status)
}
const isExist = function (url) {
  return requiredTokenURL.includes(url) || url.includes(queryURL)
}
const errorHandlers = {
  401: function () {
    console.log('401错误处理')
  }
}
const toLoginPage = function () {
  router.push({
    path: '/login',
    query: {
      back: router.currentRoute.fullPath
    }
  })
}
const errnoHandlers = {
  9998: function () {
    toLoginPage()
  }
}
const errorHandle = function (err) {
  const status = err.response.status
  const errorHandler = errorHandlers[status]
  errorHandler && errorHandler()
  return Promise.reject(err)
}
const setConfigAuthorization = function (config) {
  const token = getToken(ACCESSTOKEN)
  if (isExist(config.url) && token) {
    config.headers.token = token
  }
}

const responseErrnoHandler = function (errno) {
  const errnoHandler = errnoHandlers[errno]
  errnoHandler && errnoHandler()
  return Boolean(errnoHandler)
}
export {
  statusIsPass,
  errorHandle,
  setConfigAuthorization,
  responseErrnoHandler
}
